<?php
/**
 * Exports translated data to PHP constants
 * 
 * 
 * @uses classes/babel/Find_Files.php
 * @package BABEL
 * @since   BABEL 0.1.0
 * @version $Id: export.php 766 2008-05-14 08:52:59Z bjori $
 * @copyright Copyright (C) 2008 Hannes Magnusson
 * @copyright Copyright (C) 2008 Anders Bjørnstad
 * @copyright Copyright (C) 2008 Frank Bølviken
 * @author  Hannes Magnusson
 * @author  Anders Bjørnstad
 * @author 	Frank Bølviken
 * @author 	Audun Skjelvan
 * @license LGPL
 */

include 'includes/babel/babel_constants.php';

require $ROOT_DIR . "classes/babel/BabelZipArchive.php";

$action = isset($_GET["action"]) ? $_GET["action"] : "start";
if ($action != "finish") {
	require $ROOT_DIR . "includes/babel/prepend_gui.php";
} else {
	require $ROOT_DIR . "includes/babel/prepend_no_gui.php";
}

$language = isset($_GET["language"]) ? $_GET["language"] : false;

$obj_tpl->setFile("export_error", "babel/errorpage.html");
$obj_tpl->setBlock("export_error", "export_error", "export_error_ref");

$rowCount = 0;
switch($action) {
case "start":
	$obj_tpl->setFile("export_languagelist", "babel/export_languagelist.html");
	$obj_tpl->setBlock("export_languagelist", "LANGUAGE_LINKS", "lang_ref");
	
	/* {{{ Write out the language selection list */
	if (!PDODB::runQuery("SELECT langcode, name FROM babel_languages WHERE status=?", array(_BABEL_LANGUAGE_ENABLED), $stmt)) {
		throw new Exception("Query failed");
	}
	
	foreach($stmt as $row) {
		$obj_tpl->setVar(array(
			'ROW_TR_BGCOLOR'	=> ++$rowCount % 2 ? '#EEEEEE' : '#DDDDDD',
			'TXT_LANGCODE' 		=> $row["langcode"],
			'TXT_LANGNAME' 		=> $row["name"],
		));	
		$obj_tpl->parse("lang_ref", "LANGUAGE_LINKS", true);
	}
	$obj_tpl->pparse("export_languagelist", "export_languagelist", true);
	break;
/* }}} */

case "list":
	$obj_tpl->setFile("export_filelist", "babel/export_filelist.html");
	$obj_tpl->setBlock("export_filelist", "FILE_LINKS", "file_ref");

/* {{{ Write out the filenames available */
	if (!PDODB::runQuery("SELECT file_id, name FROM babel_files", null, $stmt)) {
		throw new Exception ("Query failed");
	}

	$obj_tpl->setVar("TXT_LANGUAGE", $language);
	foreach($stmt as $row) {
		$obj_tpl->setVar(array(
			'ROW_TR_BGCOLOR' 	=> ++$rowCount % 2 ? '#EEEEEE' : '#DDDDDD',
			'TXT_FILEID'		=> $row["file_id"],
			'TXT_FILENAME'		=> $row["name"],
		));
		$obj_tpl->parse("file_ref", "FILE_LINKS", true);
	}

	$obj_tpl->setBlock("babel_export", "NO_FILES", "nofileref");
	if ($rowCount == 0) {
		$obj_tpl->pparse("nofileref", "NO_FILES", true);
	}
	$obj_tpl->pparse("export_filelist", "export_filelist", true);
	break;
/* }}} */

case "finish":
/* {{{ Export the picked files */
	
	if (!isset($_POST["files"]) || !count($_POST["files"])) {
		require $ROOT_DIR . "includes/babel/prepend_gui.php";
		throw new Exception("No files");
	}
	$obj_tpl->setFile("export_filewritten", "babel/export_filewritten.html");
	$obj_tpl->setBlock("export_filewritten", "DEBUG_MESSAGES", "debug_ref");	


	try {
		$row = PDODB::execQueryFetch(<<< SQL
SELECT
		language_id AS id,
		name AS langname
	FROM babel_languages
	WHERE babel_languages.langcode=?
	LIMIT 1
SQL
		, PDO::FETCH_ASSOC, array($language));
	} catch(Exception $e) {
		$obj_tpl->setVar("TXT_DEBUG_MESSAGES", "Unknown language chosen, $language");
		$obj_tpl->pparse("debug_ref", "DEBUG_MESSAGES", true);
		break;
	}
	$langid = $row[0]["id"];
	$langname = $row[0]["langname"];
	
	$obj_tpl->setVar("VAR_LANGNAME", $langname);

$db = PDODB::connect();
$stmt_export = $db->prepare(<<< SQL
SELECT
	babel_originals.constant_name AS constname,
	babel_translations.translated_string AS string,
	babel_translations.revision AS revision
FROM
	babel_originals,
	babel_translations,
	babel_values
WHERE
	babel_originals.file_id = ?
		AND babel_translations.language_id = ?
		AND babel_translations.value_id = babel_values.original_id
		AND babel_values.original_id = babel_originals.original_id
		AND babel_translations.status = ?
ORDER BY
	babel_translations.changed_date
SQL
);

$stmt_filename = $db->prepare(<<< SQL
SELECT
	babel_files.name AS filename,
	babel_files.revision AS revision
FROM
	babel_files
WHERE
	babel_files.file_id = ?
SQL
);
	$rowCount = 1;
	$total_const_counter = 0;
	$fn = tempnam(sys_get_temp_dir(), "zip");
	$fileobj = new BabelZipArchive($fn, ZipArchive::CREATE|ZipArchive::EXCL|ZipArchive::OVERWRITE);
	foreach($_POST["files"] as $fileid => $unused) {
		$const_counter = 0;
		
		$obj_tpl->setVar(array(
			'ROW_TR_BGCOLOR'	=> $rowCount % 2 ? '#EEEEEE' : '#DDDDDD',
			'VAR_ROWCOUNT'		=> $rowCount,
		));	
		$rowCount++;	
		
		if (!$stmt_filename->execute(array((int)$fileid))) {
			throw new Exception ("Query failed");
		}
		$row = $stmt_filename->fetch();
		$filename = $row["filename"];

		if (!$stmt_export->execute(array((int)$fileid, $langid, BABEL_TRANSLATE_STATUS_APPROVED))) {
			throw new Exception("Query failed");
		}

		if ($stmt_export->rowCount() == 0) { 
			$obj_tpl->setVar(array(
				'TXT_DEBUG_MESSAGES'		=> $filename,
				'VAR_COUNT_CONSTANTS'		=> $const_counter,
				'VAR_FILE_EXPORT_STATUS'	=> "No constants found."
			));
			$obj_tpl->parse("debug_ref", "DEBUG_MESSAGES", true);
			continue;
		}

		$xw = new XMLWriter();
		$xw->openMemory();
		$xw->setIndent(true);
		$xw->setIndentString("  "); 
		$xw->startDocument("1.0", "UTF-8");
		$xw->startElement("file");
		$xw->writeAttribute("revision", $row["revision"]);
		$xw->writeAttribute("name", $filename);

		foreach($stmt_export as $row) {
			$xw->startElement("entry");
			$xw->writeAttribute("revision", $row["revision"]);
			$xw->writeAttribute("name", $row["constname"]);
			$xw->text($row["string"]);
			$xw->endElement();
		}
		$xw->endElement();

		$fileobj->addFromString($filename.$langcode, $xw->flush());

		$const_counter = $stmt_export->rowCount();
		$total_const_counter += $const_counter;
		/* all constants in the original file are available in the new file */
		$obj_tpl->setVar(array(
			'TXT_DEBUG_MESSAGES'		=> $filename,
			'VAR_COUNT_CONSTANTS'		=> $const_counter,
			'VAR_FILE_EXPORT_STATUS'	=> "Ok!",
			'VAR_TOTAL_CONSTANTS'		=> $total_const_counter,
		));
		$obj_tpl->parse("debug_ref", "DEBUG_MESSAGES", true);
	}
	$fileobj->close();
	ob_end_clean();
	header("Content-type: application/octet-stream");
	header('Content-Disposition: attachment; filename="translations.zip"');
	readfile($fn);
	unlink($fn);
	exit;

	break;
	/* }}} */
}

$obj_tpl->setVar("ROW_TR_BGCOLOR", $rowCount % 2 ? '#EEEEEE' : '#DDDDDD');
$obj_tpl->parse("export_filewritten","export_filewritten");
$obj_tpl->p("export_filewritten");

